package cn.powerone.scm.service.impl;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

import cn.powerone.common.utils.DateUtils;
import cn.powerone.common.utils.poi.ExcelUtil;
import cn.powerone.scm.domain.*;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.powerone.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import cn.powerone.scm.mapper.ScmCustomerQuotesMapper;
import cn.powerone.scm.service.IScmCustomerQuotesService;

/**
 * 客户报价单Service业务层处理
 * 
 * @author PowerOne
 * @date 2025-07-02
 */
@Service
public class ScmCustomerQuotesServiceImpl implements IScmCustomerQuotesService 
{
    @Autowired
    private ScmCustomerQuotesMapper scmCustomerQuotesMapper;

    /**
     * 查询客户报价单
     * 
     * @param id 客户报价单主键
     * @return 客户报价单
     */
    @Override
    public ScmCustomerQuotes selectScmCustomerQuotesById(Long id)
    {
        return scmCustomerQuotesMapper.selectScmCustomerQuotesById(id);
    }

    /**
     * 查询客户报价单列表
     * 
     * @param scmCustomerQuotes 客户报价单
     * @return 客户报价单
     */
    @Override
    public List<ScmCustomerQuotes> selectScmCustomerQuotesList(ScmCustomerQuotes scmCustomerQuotes)
    {
        return scmCustomerQuotesMapper.selectScmCustomerQuotesList(scmCustomerQuotes);
    }

    /**
     * 新增客户报价单
     * 
     * @param scmCustomerQuotes 客户报价单
     * @return 结果
     */
    @Transactional
    @Override
    public int insertScmCustomerQuotes(ScmCustomerQuotes scmCustomerQuotes)
    {
        scmCustomerQuotes.setCreateTime(DateUtils.getNowDate());
        int rows = scmCustomerQuotesMapper.insertScmCustomerQuotes(scmCustomerQuotes);
        insertScmCustomerQuoteItems(scmCustomerQuotes);
        return rows;
    }

    /**
     * 修改客户报价单
     * 
     * @param scmCustomerQuotes 客户报价单
     * @return 结果
     */
    @Transactional
    @Override
    public int updateScmCustomerQuotes(ScmCustomerQuotes scmCustomerQuotes)
    {
        scmCustomerQuotes.setUpdateTime(DateUtils.getNowDate());
        scmCustomerQuotesMapper.deleteScmCustomerQuoteItemsByQuoteId(scmCustomerQuotes.getId());
        insertScmCustomerQuoteItems(scmCustomerQuotes);
        return scmCustomerQuotesMapper.updateScmCustomerQuotes(scmCustomerQuotes);
    }

    /**
     * 批量删除客户报价单
     * 
     * @param ids 需要删除的客户报价单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteScmCustomerQuotesByIds(Long[] ids)
    {
        scmCustomerQuotesMapper.deleteScmCustomerQuoteItemsByQuoteIds(ids);
        return scmCustomerQuotesMapper.deleteScmCustomerQuotesByIds(ids);
    }

    /**
     * 删除客户报价单信息
     * 
     * @param id 客户报价单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteScmCustomerQuotesById(Long id)
    {
        scmCustomerQuotesMapper.deleteScmCustomerQuoteItemsByQuoteId(id);
        return scmCustomerQuotesMapper.deleteScmCustomerQuotesById(id);
    }

    /**
     * 新增客户报价单额外明细信息
     * 
     * @param scmCustomerQuotes 客户报价单对象
     */
    public void insertScmCustomerQuoteItems(ScmCustomerQuotes scmCustomerQuotes)
    {
        List<ScmCustomerQuoteItems> scmCustomerQuoteItemsList = scmCustomerQuotes.getScmCustomerQuoteItemsList();
        Long id = scmCustomerQuotes.getId();
        if (StringUtils.isNotNull(scmCustomerQuoteItemsList))
        {
            List<ScmCustomerQuoteItems> list = new ArrayList<ScmCustomerQuoteItems>();
            for (ScmCustomerQuoteItems scmCustomerQuoteItems : scmCustomerQuoteItemsList)
            {
                scmCustomerQuoteItems.setQuoteId(id);
                list.add(scmCustomerQuoteItems);
            }
            if (list.size() > 0)
            {
                scmCustomerQuotesMapper.batchScmCustomerQuoteItems(list);
            }
        }
    }

    /**
     * 通过ID查询客户报价单
     *
     * @param supplierQuoteId 供应商报价单ID
     * @return 客户报价单
     */
    @Override
    public ScmCustomerQuotes selectScmCustomerQuotesBySupplierQuoteId(Long supplierQuoteId){
        return scmCustomerQuotesMapper.selectScmCustomerQuotesBySupplierQuoteId(supplierQuoteId);
    }

    /**
     * 通过项目ID查询客户报价单
     *
     * @param projectId 项目ID
     * @return 客户报价单
     */
    @Override
    public List<ScmCustomerQuotes> selectScmCustomerQuotesListByProjectId(Long projectId) {
        return scmCustomerQuotesMapper.selectScmCustomerQuotesListByProjectId(projectId);
    }

    @Override
    public void exportExcelByTemplate(HttpServletResponse response, ScmProjects scmProjects, ScmCustomer scmCustomer, List<ScmCustomerQuotes> scmCustomerQuotesList, String templateName) throws IOException {
        if(!scmCustomerQuotesList.isEmpty()) {
            // 读取模板并且按照供应商生成sheet
            InputStream templateStream = ExcelUtil.class.getClassLoader().getResourceAsStream("template/" + templateName);
            if (templateStream == null) {
                throw new FileNotFoundException("模板文件未找到");
            }
            Workbook workbook = WorkbookFactory.create(templateStream);

            Sheet sheet = workbook.getSheet(scmCustomer.getNickname());
            int totalInsert = scmCustomerQuotesList.size() - 1;
            for (Row row : sheet) {
                Cell cell = row.getCell(0);
                if (cell !=null) {
                    if (cell.getCellType() == CellType.STRING && cell.getStringCellValue().contentEquals("${seq}")) {
                        int insertRowIndex = row.getRowNum() + 1;
                        int lastRowNum = sheet.getLastRowNum();
                        sheet.shiftRows(insertRowIndex, lastRowNum, totalInsert);
                        for (int i = 0; i < totalInsert; i++) {
                            Row newRow = sheet.createRow(insertRowIndex);
                            insertRowIndex++;
                            newRow.setHeight(row.getHeight());

                            // 复制所有单元格内容、样式和注释
                            for (int colIndex = 0; colIndex <= row.getLastCellNum(); colIndex++) {
                                Cell sourceCell = row.getCell(colIndex);
                                if (sourceCell == null) {
                                    continue;
                                }

                                // 创建目标单元格
                                Cell targetCell = newRow.createCell(colIndex);

                                // 复制单元格值
                                ExcelUtil.copyCellValue(sourceCell, targetCell);

                                // 复制单元格样式
                                ExcelUtil.copyCellStyle(workbook, sourceCell, targetCell);

                                // 复制单元格注释
                                ExcelUtil.copyCellComment(sheet, sourceCell, targetCell);
                            }
                        }
                        break;
                    }
                }
            }

            processSheetPlaceholders(sheet, scmProjects, scmCustomer, scmCustomerQuotesList);

            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            workbook.write(response.getOutputStream());

            workbook.close();
            templateStream.close();
        }
    }

    /**
     * 处理单个工作表中的占位符
     */
    private static void processSheetPlaceholders(Sheet sheet, ScmProjects scmProjects, ScmCustomer scmCustomer, List<ScmCustomerQuotes> scmCustomerQuotes) {

        Map<String, String> customerPlaceholders = getCustomerPlaceholders(scmCustomer, scmProjects);
        Map<String, String> customerQuotesPlaceholders = new HashMap<>();

        int index = 0;
        boolean tableFlag = false;
        String updatedValue;
        for (Row row : sheet) {
            if (row.getCell(0) != null) {
                if (row.getCell(0).getStringCellValue().contentEquals("${seq}")) {
                    customerQuotesPlaceholders = getCustomerQuotesPlaceholders(scmCustomerQuotes.get(index), index+1);
                    index++;
                    tableFlag = true;
                }
            }
            for (Cell cell : row) {
                if (Objects.requireNonNull(cell.getCellType()) == CellType.STRING) {
                    String cellValue = cell.getStringCellValue();
                    if (cellValue.startsWith("${")) {
                        if (tableFlag) {
                            updatedValue = replacePlaceholders(cellValue, customerQuotesPlaceholders);
                        } else {
                            updatedValue = replacePlaceholders(cellValue, customerPlaceholders);
                        }
                        cell.setCellValue(updatedValue);
                        if (cellValue.contentEquals("${remarks}")) {
                            tableFlag = false;
                        }
                    }
                }
            }
        }
    }

    private static Map<String, String> getCustomerPlaceholders(ScmCustomer scmCustomer, ScmProjects scmProjects) {
        Map<String, String> placeholders = new HashMap<>();
        placeholders.put("customerName", scmCustomer.getName());
        placeholders.put("customerAddress", scmCustomer.getAddress());

        StringBuilder contactsBuilder = new StringBuilder();
        for (ScmCustomerContacts scmCustomerContacts : scmCustomer.getScmCustomerContactsList()) {
            contactsBuilder.append(scmCustomerContacts.getContactName()).append(" ");
        }
        placeholders.put("customerContacts", contactsBuilder.toString());
        placeholders.put("customerTelephone", scmCustomer.getTelephone());
        placeholders.put("customerEmail", scmCustomer.getEmail());
        placeholders.put("customerCurrency", scmProjects.getCustomerCurrency());
        return placeholders;
    }

    private static Map<String, String> getCustomerQuotesPlaceholders(ScmCustomerQuotes scmCustomerQuotes, int seq) {
        Map<String, String> placeholders = new HashMap<>();
        placeholders.put("seq", String.valueOf(seq));
        placeholders.put("drawingNumber", scmCustomerQuotes.getDrawingNumber());
        placeholders.put("productName", scmCustomerQuotes.getScmProjectProducts().getProductName());
        placeholders.put("material", scmCustomerQuotes.getMaterial());
        BigDecimal massLot = scmCustomerQuotes.getMassLot();
        placeholders.put("massLot", massLot.toString());
        placeholders.put("massUnit", scmCustomerQuotes.getMassUnit());
        BigDecimal massUnitPrice = scmCustomerQuotes.getMassUnitPrice();
        placeholders.put("massUnitPrice", massUnitPrice.toString());
        placeholders.put("remarks", scmCustomerQuotes.getRemarks());
        return placeholders;
    }

    /**
     * 替换文本中的占位符
     */
    private static String replacePlaceholders(String text, Map<String, String> placeholders) {
        String result = text;
        for (Map.Entry<String, String> entry : placeholders.entrySet()) {
            String placeholder = "${" + entry.getKey() + "}";
            result = result.replace(placeholder, entry.getValue());
        }
        return result;
    }
}
